<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------

namespace app\helper;

/**
 *
 * 要求安装phpredis扩展：https://github.com/nicolasff/phpredis
 */
class Cache
{
    /**
     * 一个值
     *
     * @param string $key
     * @param integer $id
     * @return void
     */
    public static function val(string $key, int $id)
    {
        $name = redis()->hget($key, $id);
        return $name;
    }
    /**
     * 多个值
     *
     * @param string $key
     * @param array $ids
     * @return array
     */
    public static function vals(string $key, array $ids): array
    {
        if(count($ids) === 0) return [];
        $rows = redis()->hmget($key, $ids);
        return $rows;
    }
    /**
     * 多列信息
     *
     * @param string $key
     * @param integer $id
     * @param string $cols
     * @return array
     */
    public static function col(string $key, int $id, string $cols = 'name'): array
    {
        $view = redis()->hget($key, $id);
        $view = unserialize($view);

        $cols = explode(',', $cols);
        if(count($cols)===1){
            return $view[$cols[0]];
        }
        return array_intersect_key($view, array_flip($cols));
    }
    /**
     * 多行多列信息
     *
     * @param string $key
     * @param array $ids
     * @param string $cols
     * @return array
     */
    public static function cols(string $key, array $ids, string $cols = 'name'): array
    {
        if(count($ids) === 0) return [];
        $rows = redis()->hmget($key, $ids);
        $data = [];
        $cols = explode(',', $cols);
        foreach($rows as $row){
            $row = unserialize($row);
            $data[] = count($cols)===1 ? $row[$cols[0]] : array_intersect_key($row, array_flip($cols));
        }
        return $data;
    }
    public static function ids(array $list, string $field = 'item_id', string $items = 'items'){
        $ids = [];
        foreach($list as $row){
            $ids = array_merge($ids, array_column($row[$items], $field));
        }
        return $ids;
    }
    /**
     * 合并多行多列信息
     *
     * @param array $list
     * @param array $views
     * @param string $key
     * @return void
     */
    public static function merge(array $list, array $views, string $key = 'item_id'){
        foreach($list as $k => $row){
            isset($row[$key]) && ($list[$k] += $views[$row[$key]]);
        }
        return $list;
    }
}
